<template>
    <div>
        <Table :columns="columns" :paginatedData="paginatedData" :btnList="btnList" :btnListTable="btnListTable"
            :isFixedColumn="true" :isSelected="true" :tableLoading="loading" @pageSize="handlePageSize"
            @currentPage="handleCurrentPage" @switch="handleSwitch">
            <!-- 条件组,插槽 -->
            <template #default>
                <el-form :inline="true" :model="formBtnList" class="demo-form-inline">
                    <el-form-item label="">
                        <el-input v-model="formBtnList.commodity" style="max-width: 600px" placeholder="输入商品名称/货号"
                            class="input-with-select">
                            <template #append>
                                <el-button @click="handleQuery" :icon="Search" />
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="分类:">
                        <el-select v-model="formBtnList.classification" placeholder="选择分类" clearable
                            style="width: 200px;">
                            <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="品牌:">
                        <el-select v-model="formBtnList.brand" placeholder="选择品牌" clearable style="width: 180px;">
                            <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-form>
            </template>
        </Table>
    </div>
    <!-- 抽屉 -->
    <el-drawer v-model="tableShow" title="添加商品" direction="rtl" size="50%" :show-close="false">
        <template #header="{ close, titleId, titleClass }">
            <h4 :id="titleId" :class="titleClass" class="titleH4"><span @click="close">
                    <el-icon>
                        <Close />
                    </el-icon></span>
                添加商品</h4>
        </template>
        <div>
            <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
                <el-tab-pane label="基本信息" name="first">
                    <div style="margin-top: 20px">
                        <el-form ref="ruleFormRef" style="max-width: 900px" :model="ruleForm" :rules="rules"
                            label-width="auto" class="demo-ruleForm" :size="formSize" status-icon>
                            <el-form-item label="商品类型" prop="type">
                                <el-radio-group class="radioList" v-model="ruleForm.type">
                                    <el-radio value="1" size="large" border>普通商品</el-radio>
                                    <el-radio value="2" size="large" border>虚拟商品
                                        <el-tooltip class="box-item" effect="dark" content="虚拟的商品" placement="bottom">
                                            <el-icon>
                                                <QuestionFilled />
                                            </el-icon>
                                        </el-tooltip>
                                    </el-radio>
                                    <el-radio value="3" size="large" border>卡密商品
                                        <el-tooltip class="box-item" effect="dark" content="卡密的商品" placement="bottom">
                                            <el-icon>
                                                <QuestionFilled />
                                            </el-icon>
                                        </el-tooltip>
                                    </el-radio>
                                    <el-radio value="4" size="large" border>付费内容
                                        <el-tooltip class="box-item" effect="dark" content="付费的内容" placement="bottom">
                                            <el-icon>
                                                <QuestionFilled />
                                            </el-icon>
                                        </el-tooltip>
                                    </el-radio>
                                </el-radio-group>
                            </el-form-item>
                            <el-form-item label="商品相册" prop="">
                                <draggable v-model="fileList" class="drag_img" item-key="url">
                                    <template #item="{ element }">
                                        <div class="img_item">
                                            <img :src="element.url" alt="" style="width: 100%;height: 100%;">
                                            <!-- 图片的遮罩 预览 和 删除 -->
                                            <div class="shade">
                                                <div class="img_operate">
                                                    <el-icon>
                                                        <ZoomIn @click="handlePictureCardPreview(element)"
                                                            style="cursor:pointer;" />
                                                    </el-icon>
                                                    <el-icon style="margin: 0 10px;">
                                                        <DeleteFilled @click="handleRemove(element)"
                                                            style="cursor: pointer;" />
                                                    </el-icon>
                                                </div>
                                            </div>
                                        </div>
                                    </template>
                                </draggable>
                                <el-upload v-model:file-list="fileList"
                                    action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
                                    list-type="picture-card" :on-preview="handlePictureCardPreview"
                                    :on-remove="handleRemove" :show-file-list="false">
                                    <el-icon>
                                        <Picture />
                                    </el-icon>
                                </el-upload>
                                <el-dialog v-model="dialogVisible">
                                    <img w-full :src="dialogImageUrl" alt="Preview Image" />
                                </el-dialog>
                            </el-form-item>
                            <span class="imageText">您可以通过拖接来调整相册图片顺序，第一张图将作为商品主图展示</span>
                            <el-form-item label="商品名称" prop="name">
                                <el-input v-model="ruleForm.name" placeholder="请输入商品名称" clearable />
                            </el-form-item>
                            <el-row>
                                <el-col :span="21">
                                    <el-form-item label="搜索关键词" prop="keyword">
                                        <el-input v-model="ruleForm.keyword" placeholder="" clearable />
                                        <span class="described">用空格分隔，为空时会自根据商品名称分词</span>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="3">
                                    <el-form-item>
                                        <el-button style="margin-left: 10px;" type=""
                                            @click="updateKeywords">更新关键词</el-button>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-form-item label="商品类目" prop="category">
                                <el-select v-model="ruleForm.category" placeholder="选择分类">
                                    <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="商品售价" prop="price">
                                <el-input class="no_number" type="number" v-model="ruleForm.price" placeholder=""
                                    clearable @input="priceInput">
                                    <template #prepend><span style="color: black;">￥</span></template>
                                </el-input>
                            </el-form-item>
                            <el-form-item label="市场价" prop="marketPrice">
                                <el-input class="no_number" type="number" v-model="ruleForm.marketPrice" placeholder=""
                                    clearable @input="marketPriceInput">
                                </el-input>
                                <span class="described">划线价格，不填则不显示</span>
                            </el-form-item>
                            <el-form-item label="商品库存" prop="inventory">
                                <el-input class="no_number" type="number" v-model="ruleForm.inventory" placeholder=""
                                    clearable>
                                </el-input>
                                <span class="described">库存在商品存在货品时编辑无效，库存数值取决于其规格库存数量</span>
                            </el-form-item>
                            <el-form-item label="限购数量" prop="purchase">
                                <el-input class="no_number" type="number" v-model="ruleForm.purchase" placeholder=""
                                    clearable>
                                </el-input>
                                <span class="described">商品限购数量，为0则不限制</span>
                            </el-form-item>
                            <el-form-item label="商品描述" prop="partDescription">
                                <el-input v-model="ruleForm.partDescription" :autosize="{ minRows: 2, maxRows: 4 }"
                                    type="textarea" placeholder="" />
                                <span class="described">该描述一般会高亮出现在商品名称后面</span>
                            </el-form-item>
                            <el-form-item label="商品编码" prop="commodityCode">
                                <el-input v-model="ruleForm.commodityCode" placeholder="" clearable />
                                <span class="described">如果您不输入商品编码，系统将自动生成一个唯一的编码</span>
                            </el-form-item>
                        </el-form>
                    </div>
                </el-tab-pane>
                <el-tab-pane label="商品描述" name="second">Config</el-tab-pane>
                <el-tab-pane label="属性规格" name="third">Role</el-tab-pane>
                <el-tab-pane label="其它信息" name="fourth">Task</el-tab-pane>
            </el-tabs>
        </div>
        <template #footer>
            <div>
                <el-button @click="cancelClick">取消</el-button>
                <el-button type="primary" @click="confirmClick">确认</el-button>
            </div>
        </template>
    </el-drawer>
</template>

<script setup lang='ts' name="SecondaryPage">
import { ref, reactive } from 'vue'
import type { TabsPaneContext } from 'element-plus'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import type { UploadProps, UploadUserFile } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import draggable from "vuedraggable";
import Table from '../components/Table.vue';
import { require } from '../utils/require';

// 表格相关 开始
const loading = false
// 表头数据
const columns = ref([
    { prop: 'profile_picture_url', label: '商品主图', width: '110', isImg: true, height: 50 },
    { prop: 'information', label: '商品信息', width: '140', doubleRow: true, text1: '货号', text2: '售价' },
    { prop: 'inventory', label: '库存', width: '90' },
    { prop: 'listed', label: '是否上架', width: '110', isSwitch: true, },
]);
// 表格数据
const paginatedData = ref([
    { profile_picture_url: require('@/assets/logo.png'), information: { text1: '111', text2: '2222' }, inventory: 999, listed: false, },
    { profile_picture_url: require('@/assets/image/giegie.jpg'), inventory: 888, listed: true },
]);
// 查询条件
const formBtnList = reactive({
    commodity: '',
    classification: '',
    brand: '',
    pageSize: 10,
    currentPage: 1,
})
const addCommodity = () => {
    tableShow.value = true
}
// 按钮组
const btnList = [
    { name: '添加商品', type: 'info', click: addCommodity, icon: 'Plus' },
]
// 操作列按钮事件
const pricingDetail = () => {
    console.log('pricingDetail')
}
const reject = () => {
    console.log('reject')
}
// 操作列按钮组
const btnListTable = ref([
    { name: '编辑', type: 'primary', click: pricingDetail },
    { name: '删除', type: 'primary', click: reject },
])
// 分页事件触发
const handlePageSize = (pageSize: number) => {// 每页大小
    // console.log('handlePageSize', pageSize);
    formBtnList.pageSize = pageSize
};
const handleCurrentPage = (currentPage: number) => {// 页码
    // console.log('handleCurrentPage', currentPage);
    formBtnList.currentPage = currentPage
};
// 查询
const handleQuery = (() => {

})
// 表格相关 结束
const tableShow = ref(false)
// 标签页
const activeName = ref('first')
const handleClick = (tab: TabsPaneContext, event: Event) => {
    // console.log(tab, event)
}
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
// 表单内容
interface RuleForm {
    name: string
    type: string
    keyword: string
    category: string
    price: string
    marketPrice: string
    inventory: string
    purchase: string
    partDescription: string
    commodityCode: string
}
const ruleForm = reactive<RuleForm>({
    name: '',
    type: '1',
    keyword: '',
    category: '',
    price: '',
    marketPrice: '',
    inventory: '',
    purchase: '0',
    partDescription: '',
    commodityCode: '',
})
const rules = reactive<FormRules<RuleForm>>({
    name: [
        { required: true, message: '此项为必填项', trigger: 'blur' },
    ],
    type: [
        { required: true, message: '此项为必填项', trigger: 'blur' },
    ],
    category: [
        { required: true, message: '此项为必填项', trigger: 'blur' },
    ],
})
const updateKeywords = (() => {
    // if (!ruleForm.name) {
    //     ElMessage({
    //         type: 'error',
    //         message: '请先输入商品名称！',
    //     })
    //     return
    // } else {
    //     ruleForm.keyword = ruleForm.name
    // }
})
const priceInput = ((val: string) => {
    ruleForm.price = processedAmount(val)
})
const marketPriceInput = ((val: string) => {
    // if (val.startsWith('.')) {
    //     ruleForm.marketPrice = '0' + val
    // }
    // if (val) {
    //     ruleForm.marketPrice = parseFloat(Number(val).toFixed(2)).toString()
    // }
    ruleForm.marketPrice = processedAmount(val)
})
const processedAmount = (number: string) => {
    if (number.startsWith('.')) {
        return '0' + number
    } else if (number) {
        return parseFloat(Number(number).toFixed(2)).toString()
    } else {
        return number
    }
}
const categoryOptions = [
    {
        value: 'Option1',
        label: 'Option1',
    },
    {
        value: 'Option2',
        label: 'Option2',
    },
]
const fileList = ref<UploadUserFile[]>([
    {
        name: 'food.jpeg',
        url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
    },
    {
        name: 'plant-1.png',
        url: '/images/plant-1.png',
    },
    {
        name: 'giegie',
        url: require('@/assets/image/giegie.jpg'),
    },
])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
// elementPlus 原删除方法
// const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
//     console.log(uploadFile, uploadFiles)
// }
interface UploadFile {
    status: string;
    url: string;
}
const handleRemove = (uploadFile: UploadFile) => {
    // console.log(uploadFile);
    if (uploadFile?.status && uploadFile?.status === "success") {
        const address = uploadFile.url
        fileList.value = fileList.value.filter(i => i.url !== address)
    }
};

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}

const cancelClick = (() => {
    tableShow.value = false
})
const confirmClick = (() => {

})
// 开关事件
const handleSwitch = ((row: any) => {
    console.log('row', row);

})
</script>
<style lang='scss' scoped>
.titleH4 {
    color: black;

    span {
        cursor: pointer;
        display: inline-block;
        font-weight: 100;
        margin-right: 20px;
    }
}

:deep(.no_number input::-webkit-inner-spin-button),
:deep(.no_number input::-webkit-outer-spin-button) {
    -webkit-appearance: none !important;
}

:deep(.no_number input[type="number"]) {
    -moz-appearance: textfield;
}

.demo-tabs {
    .radioList {
        :deep(.el-icon) {
            vertical-align: middle;
        }
    }
}

:deep(.el-radio-group) {
    .el-radio {
        min-width: 170px;
        margin-bottom: 10px;
    }
}

:deep(.el-upload--picture-card) {
    width: 80px;
    height: 80px;
}

:deep(.el-upload-list--picture-card) {
    --el-upload-list-picture-card-size: 82px;
}

.drag_img {
    display: flex;
    // width: 100%;
    flex-wrap: wrap;

    .img_item {
        height: 90px;
        width: 90px;
        padding: 5px 10px 5px 0;
        box-sizing: border-box;
        position: relative;
    }
}

.shade {
    position: absolute;
    left: 0;
    top: 5px;
    right: 10px;
    bottom: 5px;
    cursor: default;
    text-align: center;
    // padding: 0 10px 10px 0;
    color: #fff;
    opacity: 0;
    box-sizing: border-box;
    font-size: 20px;
    background-color: rgba(0, 0, 0, 0.5);
    -webkit-transition: opacity 0.3s;
    transition: opacity 0.3s;
    display: flex;
    justify-content: center;
    align-items: center;

    .img_operate {
        padding: 10px 0 0 10px;
    }

    &:hover {
        opacity: 1;
    }
}

:deep(.el-dialog__body) {
    img {
        width: 100%;
    }
}

.imageText {
    display: inline-block;
    font-size: 12px;
    margin-left: 10%;
    margin-bottom: 20px;
    color: #a3a3a3;
}

.described {
    font-size: 12px;
    color: #a3a3a3;
}
</style>